package com.ltt.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectResult;
import com.ltt.utils.picutils.PicUtil;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author ‘李天泰’
 * @version 1.0
 * @description: 上传文件的根据类
 * @date 2023/5/1 15:36
 */

public class FileUtils {
    private static final String endpoint = "oss-cn-beijing.aliyuncs.com";
    private static final String accessKeyId = "LTAI5tNsATZP4rG3Z93J18xM";
    private static final String accessKeySecret = "070QvOeoYahaQnbs99mgCAk0dCOJg2";
    private static final String bucketName = "student-rousece";

    public static String uploadImage(byte[] imgData,String originalName) {
        // 创建OSSClient实例。
        System.out.println("endpoint:" + endpoint + ",accessKeyId:" + accessKeyId + ",accessKeySecret:" + accessKeySecret + ",bucketName:" + bucketName);
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            String fileName = UUID.randomUUID() + " " + originalName;
            String preName = "https://student-rousece.oss-cn-beijing.aliyuncs.com/";

            imgData = PicUtil.compressPicForScale(imgData, 512L);
            BASE64Encoder encoder = new BASE64Encoder();
            String str = encoder.encode(imgData).trim();

            BASE64Decoder decoder = new BASE64Decoder();
            byte[] imgbyte = decoder.decodeBuffer(str);

            PutObjectResult putObjectResult = ossClient.putObject(bucketName, fileName, new ByteArrayInputStream(imgbyte));
            System.out.println("---------------------------------");
            System.out.println(putObjectResult);
            return preName + fileName;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}
